#!/usr/loca/bin/python

#-*- encoding:utf-8 -*-
import evaluator as eval
import sys
'''T'''

test_dict={}
def loadTest(labelFile):
    f = open(labelFile, 'r');
    ID = 1;
    for line in f:
        li = line.strip().split('|', 1);
        if len(li) != 2:
            print 'Wrong, STOPING....';
            return;
        test_dict[ID] = (li[0], '|'+li[1]);
        ID += 1;
    print 'All test', len(test_dict);
    f.close();

def writeTest(sortLabelFile):
    f = open(sortLabelFile, 'w');
    l = len(test_dict);
    for i in range(l):
        f.write('%s%s\n' % (test_dict[i+1][0], test_dict[i+1][1]));
    f.close();

predict_dict = {};

def loadPredict(resultFile):
    f = open(resultFile, 'r');
    for line in f:
        li = line.strip().split('\t');
        if len(li) != 4:
            print 'Wrong, STOPING...';
            return;
        queryID = int(li[0]);
        s = float(li[1]);
        l = int(li[2]);
        appID = li[3];
        if predict_dict.has_key(queryID):
            predict_dict[queryID].append((s, l, appID));
        else:
            predict_dict[queryID] = [];
            predict_dict[queryID].append((s, l, appID));
    f.close();  


def getScore(pos, l):
    s = l / 3;
    if pos < s:
        return 1;
    elif pos < 2*s:
        return 2;
    else:
        return 3;
def process(ID):
    '''This function process a given queryID, and process'''
    li = predict_dict[ID];
    print ID, test_dict[ID][0];
    li.sort();
    s = '';
    l = len(li);
    for pos, item in enumerate(li):
        s = '%s|%d:%s:%d' %(s, pos, item[2], getScore(pos, l) );
    return s;

def main(bm25file, rpfile, labelFile, sortLabelFile):
    loadTest(labelFile);
    loadPredict(rpfile);
    ndcg5_bm25 = eval.main(bm25file);
    ndcg5_rp = eval.main(rpfile);
    #print ndcg5_bm25;
    #print ndcg5_rp;
    for pos, score in enumerate(ndcg5_bm25):
        if score == 1.0:
            print pos+1,;
        if score > ndcg5_rp[pos] + 0.05:
            print pos+1, score, ndcg5_rp[pos];
            test_dict[pos+1] = (test_dict[pos+1][0], process(pos+1));
                    
    writeTest(sortLabelFile);
if __name__ == '__main__':
    bm25file = sys.argv[1];
    rpfile = sys.argv[2];
    labeldFile = sys.argv[3];
    sortLabelFile = sys.argv[4];
    main(bm25file, rpfile, labeldFile, sortLabelFile);

